package picobot.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JOptionPane;

/**
 * a class to perform a go action, the action that runs the simulation
 */
public class GoAction implements ActionListener {
	PicobotUserInterface ui;
	Timer timer;
	PicoRunning timerTask;
	protected boolean isCanceled;

	/**
	 * the constructor for GoAction that takes an PicobotUserInterface, which
	 * the action is meant for
	 * 
	 * @param ui
	 *            the picobot user interface
	 */
	public GoAction(PicobotUserInterface ui) {
		timer = new Timer();
		timerTask = new PicoRunning(ui, this);
		this.ui = ui;
	}

	/**
	 * cancels the task of the timer, note that this timer has only one task
	 */
	public void taskCancel() {
		timerTask.cancel();
		isCanceled = true;
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {

		if (isCanceled) {
			timerTask = new PicoRunning(ui, this);
			timer.scheduleAtFixedRate(timerTask, 10, 1);
		} else {
			timer.scheduleAtFixedRate(timerTask, 10, 1);
		}
	}

}

/**
 * a task class for the timer of the GoAction class this task runs the
 * simulation of the given PicobotUserInterface until the mission is completed
 * and shows a message that this is the case
 */
class PicoRunning extends TimerTask {

	PicobotUserInterface pui;
	GoAction goAction;

	/**
	 * the constructor of the PicoRunning task that takes a GoAction and a
	 * PicobotUserInterface
	 * 
	 * @param ui
	 *            is the PicobotUserInterface
	 * @param goAction
	 *            is the GoAction
	 */
	public PicoRunning(PicobotUserInterface ui, GoAction goAction) {
		pui = ui;
		this.goAction = goAction;
	}

	@Override
	public void run() {
		// as long the mission isn't completed
		if (!(pui.getSimulator().isMissionCompleted())) {
			// do a step in the simulation
			pui.getScreen().stepUpdate();
		} else {
			// if the mission is completed, cancel this task, invoke the
			// canceling of the timer and show the appropriate message
			this.cancel();
			goAction.isCanceled = true;

			JOptionPane.showMessageDialog(pui, "MISSION COMPLETE",
					"Congratulation message", JOptionPane.INFORMATION_MESSAGE);

		}
	}
}
